package translator;

import info.clearthought.layout.TableLayout;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/**
 * Created by IntelliJ IDEA.
 * User: ilya
 * Date: 28.05.11
 * Time: 10:43
 */
public class Translator extends JFrame implements ActionListener {

    public static void main(String[] args) {
        new Translator();
        new Translator();
    }

    private Map<String, String> dictionary = new HashMap<String, String>();
    private JTextArea source;
    private JTextArea dest;
    private JLabel info;

    public Translator() {
        loadDictionary();

        createInterface();

        setTitle("Задача про переводчик");
        setSize(800, 600);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        setVisible(true);
    }

    private void loadDictionary() {
        try {
            Scanner s = new Scanner(new File("dict.txt"));

            while (s.hasNext())
                dictionary.put(s.next(), s.next());

            s.close();
        } catch (FileNotFoundException e) {
            System.out.println("Не удалось прочитать словарь");
        }
    }

    private void createInterface() {
        double[] rows = {TableLayout.FILL, TableLayout.PREFERRED, TableLayout.FILL, TableLayout.PREFERRED};
        double[] cols = {TableLayout.FILL, TableLayout.PREFERRED, TableLayout.FILL};

        setLayout(new TableLayout(cols, rows));

        JButton translate = new JButton("Перевести");
        add(translate, "1 1");
        translate.addActionListener(this);

        source = new JTextArea();
        add(new JScrollPane(source), "0 0 0 2");

        dest = new JTextArea();
        add(new JScrollPane(dest), "2 0 2 2");
        dest.setEditable(false);

        info = new JLabel();
        add(info, "0 3 2 3");
    }

    public void actionPerformed(ActionEvent e) {
        Scanner wordsReader = new Scanner(source.getText());

        String translated = "";

        int allWordsCount = 0;
        int unknownWordsCount = 0;

        while (wordsReader.hasNext()) {
            String word = wordsReader.next();

            allWordsCount ++;

            boolean firstIsCapital = Character.isUpperCase(word.charAt(0));
            word = word.toLowerCase();

            String[] signs = {"...", ",", ";", "!", "?", "."};
            String ending = "";
            for (String sign : signs)
                if (word.endsWith(sign)) {
                    ending = sign;
                    word = word.substring(0, word.length() - sign.length());
                }

            String translatedWord = dictionary.get(word);
            boolean unknownWord = false;
            if (translatedWord == null) {
                translatedWord = word;

                if (!isInteger(word)) {
                    unknownWord = true;
                    unknownWordsCount ++;
                }
            }

            if (firstIsCapital)
                translatedWord = Character.toUpperCase(translatedWord.charAt(0)) + translatedWord.substring(1);

            if (unknownWord)
                translatedWord = "[" + translatedWord + "]";

            translatedWord += ending;

            //приписать пробел, если уже есть переведенный текст.
            if (!translated.equals(""))
                translated += " ";
            translated += translatedWord;
        }

        dest.setText(translated);
        info.setText("Переведено слов: " + allWordsCount + ", из них неизвестны: " + unknownWordsCount);

        showTranslationInNotepad();
    }

    private boolean isInteger(String word) {
        try {
            Integer.parseInt(word);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    private void showTranslationInNotepad() {
        PrintStream output = null;
        try {
            File outputFile = File.createTempFile("traslation-problem-", ".tmp");
            output = new PrintStream(outputFile);

            output.println(dest.getText());

            Runtime.getRuntime().exec("gedit " + outputFile.getAbsolutePath());
        } catch (IOException e) {
            System.out.println("Не удалось записать в файл");
        } finally {
            if (output != null)
                output.close();
        }
    }
}
